<?php

namespace app\common\service;

class BiaotabService
{
    public function index($article){
       
        // 获取文件路径
        $file_path = $article['new_document_path'];

        // 检查路径是否存在
        if (!is_dir($file_path)) {
            return [
                'code' => 404,
                'message' => "文件夹不存在: {$file_path}",
                'data' => null
            ];
        }
        
        $imageFiles = json_decode($article['file_path']);
        if (empty($imageFiles)) {
            return [
                'code' => 400,
                'message' => "没有找到有效的图片文件",
                'data' => null
            ];
        }

        // 默认旋转角度
        $rotation_angle = 0;
        
        // 如果有第二张图片，尝试找出最佳旋转角度
        if(!empty($imageFiles[1])){
            $count = 0;
            $image = $this->getImageJpg($file_path . '/' . $imageFiles[1]);
                    
            if (!$image) {
                return [
                    'code' => 500,
                    'message' => "图片处理失败",
                    'data' => null
                ];
            }
            
            // 尝试不同的旋转角度，找出最优角度
            $angles = [0, 90, 180, 270];
            
            
            foreach($angles as $angle) {
                $response = $this->curlMadown($image, $angle);
                if(!empty($response['markdown'])){
                    // 统计中文字符
              
                    preg_match_all('/[\x{4e00}-\x{9fa5}]/u', $response['markdown'], $matches);
                    $num = count($matches[0]);
                    if($num > $count){
                        $count = $num;
                        $rotation_angle = $angle;
                       
                    }
                }
            }
        }
       
        // 初始化结果数组
        $markdownArr = [];
        
        // 处理所有图片
        foreach($imageFiles as $key => $value){
            $imagePath = $file_path . '/' . $value;
            $processedImage = $this->getImageJpg($imagePath);
            
            if (!$processedImage) {
                continue; // 跳过处理失败的图片
            }
            
            $response = $this->curlMadown($processedImage, $rotation_angle);
            
            if(!empty($response['markdown'])){
                // 使用索引键作为数组键，确保JSON编码后保持数组结构
                $markdownArr["key{$key}"] = $response['markdown'];
            }else{
                $markdownArr["key{$key}"] = "";
            }
        }
        
        return [
            'code' => 200,
            'message' => "success",
            'data' => $markdownArr
        ];
    }

    public function getImageJpg($imagePath){
        if (pathinfo($imagePath, PATHINFO_EXTENSION) == 'tif') {
            $image  = $this->tifToJpg($imagePath);
           // 检查转换是否成功
           if (!$image  || !file_exists($image)) {
               error_log("TIF转JPG失败");
               return null;
           }
           return $image;
       }
       return $imagePath;
    }

    public function removeWSPrefix($path)
    {
        // 检查路径是否为空
        if (empty($path)) {
            return $path;
        }
        
        // 使用dirname函数直接获取路径的目录部分
        return dirname($path);
    }

        /**
     * TIF格式转JPG格式
     * @param string $tifPath TIF图片路径
     * @return string 转换后的JPG图片路径
     */
    public function tifToJpg($tifPath)
    {
        // 检查文件是否存在
        if (!file_exists($tifPath)) {
            error_log("文件不存在: $tifPath");
            return null;
        }
        
        try {
            // 使用Imagick转换格式
            $image = new \Imagick($tifPath);
            $image->setImageFormat('jpg');
            
            // 创建临时文件保存转换结果
            $jpgPath = tempnam(sys_get_temp_dir(), 'tif_converted_') . '.jpg';
            $image->writeImage($jpgPath);
            
            // 释放资源
            $image->clear();
            $image->destroy();
            
            return $jpgPath;
        } catch (\Exception $e) {
            error_log("转换图片出错: " . $e->getMessage());
            return null; // 转换失败返回null
        }
    }
    

    function curlMadown($imagePath, $rotation_angle){
        $curl = curl_init();

        $tableService = config("tableService");

        $url = $tableService . '/api/convert';
      
   
        
        // 定义boundary
        $boundary = uniqid();
        
        // 构建multipart/form-data数据
        $dataString = "";
        
        // 添加图片文件
        $dataString .= "--{$boundary}\r\n";
        $dataString .= "Content-Disposition: form-data; name=\"image_file\"; filename=\"" . basename($imagePath) . "\"\r\n";
        $dataString .= "Content-Type: application/octet-stream\r\n\r\n";
        $dataString .= file_get_contents($imagePath) . "\r\n";
        
        // 添加旋转角度
        $dataString .= "--{$boundary}\r\n";
        $dataString .= "Content-Disposition: form-data; name=\"rotation_angle\"\r\n\r\n";
        $dataString .= $rotation_angle . "\r\n";
        
        // 结束boundary
        $dataString .= "--{$boundary}--";
        
        // 设置curl选项
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $dataString);
        
        // 设置headers
        $headers = [
            'Content-Type: multipart/form-data; boundary=' . $boundary,
            'Authorization: Bearer sk-tiuvcznrtvpmjnipckrwiaotbspbpeslgbxadpwznrfdqocc'
        ];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        
        $response = curl_exec($curl);
        $error = curl_error($curl);
        curl_close($curl);
        
        if ($error) {
            error_log("cURL Error: " . $error);
            return null;
        }
        
        // 解析JSON并返回完整解码数据
        return json_decode($response, true);
    }
      
}